<?php
namespace PHPSpring\Annotation\Impl;

use PHPSpring\Annotation\IValidator;

/**
 * @InList($message?, array|string $groups?)
 * eg:
 *   @InList("1|2")
 *   @InList(list="0|1|2")
 *   @InList("0|1|2|5|8", message="用户类型不正确", groups='groups') or @InList(list="0|1|2|5|8", "用户类型不正确", groups='groups')
 * message format: '%s的值不在正确范围内' => '$fieldName的值不在正确范围内'
 */

class InList implements IValidator {

  public static function validate ($args, $fieldName, $fieldType, $fieldValue, $group=null) {
    $error = self::normalizeArguments($args);
    if ($error) {
      return $error;
    }
    if (Validation::skipValidateByGroup($group, $args)) {
      return;
    }
    $list = $args['list'];
    if (!in_array($fieldValue, $list)) {
      $error = true;
    }

    if ($error) {
      return self::getMessage($fieldName, $fieldValue, $args[Validation::MESSAGE_ARG_KEY]);
    }
  }

  public static function normalizeArguments (array &$args) {
    Validation::resetMessageArgs($args, '%s 的值不在正确范围内');
    if(!isset($args['list']) && !isset($args['default'])) {
      return '可选值范围参数缺失：$list';
    }
    $list = $args['list'] ?? $args['default'];
    if (!is_string($list)) {
      return "可选值范围参数不合法：list: {$list}";
    }
    $args['list'] = explode('|', $list);
  }

  private static function getMessage ($fieldName, $fieldValue, $message) {
    $message = str_replace('%s', $fieldName, $message);
    return $message;
  }

}
